import configparser
import os
import re

class CodeProcessor:
    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config.read('config.cfg', encoding='utf8')
        self.extensions = self.config.get('APP', 'EXTENSIONS').split(',')
        self.total = int(self.config.get('APP', 'TOTAL'))
        self.half = int(self.total / 2)
        self.pattern = None
    
    def process_folder(self, folder_paths):
        processed_lines = []
        for folder_path in folder_paths:
            for root, _, files in os.walk(folder_path):
                for file in files:
                    ext = os.path.splitext(file)[1].lower()
                    if ext in self.extensions:
                        file_path = os.path.join(root, file)
                        processed_lines.extend(self.process_file(file_path, ext))

        print("Total lines processed:", len(processed_lines))
        if len(processed_lines) > self.total:
            return processed_lines[:self.half] + processed_lines[-self.half:]
        return processed_lines
    
    def process_file(self, file_path, ext):
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 移除注释
        pattern = self.get_pattern(ext)
        if pattern:
            content = re.sub(pattern, '', content, flags=re.DOTALL|re.MULTILINE|re.IGNORECASE)
        
        # 处理换行和空行
        lines = [line for line in content.splitlines() if line.strip()]
        return lines

    def get_pattern(self, ext):
        ext = ext.replace('.', '')
        try:
            res = self.config.get('APP', f"PATTERN_{ext.upper()}")
            return rf'{res}'
        except:
            return ''

